﻿using System;
using System.Collections;
using System.ComponentModel;
using DevExpress.XtraEditors.Controls;
using RedRiver.Framework.XtraCommon.Models;

namespace RedRiver.Framework.XtraCommon.Templates{
    /// <summary>
    /// 枚举数据选择器
    /// </summary>
    public class EnumValueSelector: ValueSelector<Enum> {
        private readonly IDictionary _enumDict;

        public EnumValueSelector(Enum enumInstance)
            : this(EnumDictionary.GetEnumValuesDictionary(enumInstance.GetType())){
        }

        public EnumValueSelector(IDictionary dictionary){
            if ((dictionary == null) || (dictionary.Count == 0)){
                throw new ArgumentNullException("dictionary", @"枚举字典为空或Null");
            }
            _enumDict = dictionary;
            defaultBindingSource.DataSource = _enumDict;
            KeyColumnName = "Key";
            DisplayColumns.Add("Value");
        }

        protected override void AttachedEditValidating(object sender, CancelEventArgs e){
            //不进行检查
        }

        protected override void OnCustomDisplayText(CustomDisplayTextEventArgs e){
            if ((e.Value != null) && (_enumDict != null)){
                e.DisplayText = _enumDict[e.Value].ToString();
            } else{
                base.OnCustomDisplayText(e);
            }
        }
    }
}